<template>
  <div class="page-container">
    <div class="page-row">
      <el-card shadow="hover" style="flex:auto;margin-right:10px;" :body-style="{ padding: `20px 11px 11px` }">
        <el-row align="middle">
          <div style="margin-right:10px">
            <div class="tips-data">
              <span class="tips">阶段</span>
              <el-icon @click="openLifeSetting" size="13px" style="cursor: pointer;"><ele-Setting
                  style="color:#909399;" /></el-icon>
            </div>
            <div class="tips-data">
              <span class="tips small-tips">数量</span>
            </div>
          </div>
          <el-row style="flex:1;">
            <div class="tips-cell" v-for="(item, index) in countStage" :key="item.id">
              <div class="tips-item">
                <span :class="['tips-name', item.id < 0 ? 'red' : '']">{{ item.name }}</span>
                <el-icon v-if="index < countStage.length - 1"><ele-DArrowRight /></el-icon>
              </div>
              <!-- 当前数据 -->
              <p :class="['item-data text-red', index < countStage.length - 1 ? 'item-right' : '']">{{ item.count }}</p>
            </div>
          </el-row>
        </el-row>
      </el-card>
      <el-card shadow="hover" style="width: 500px" :body-style="{ padding: `8px 0 0` }">
        <el-row justify="space-between" style="padding: 0 11px">
          <h4>{{ year }}年度支出统计</h4>
          <el-button type="primary" link size="small">查看详情</el-button>
        </el-row>
        <el-table size="small" :data="accountList" border style="margin-top:10px">
          <el-table-column :label="`${year}年度总预算(元)`" align="center" prop="reserveAccount"></el-table-column>
          <el-table-column label="年度累计支出(元)" align="center" prop="outlayAccount"></el-table-column>
          <el-table-column label="年度剩余预算(元)" align="center" prop="leaseAccount"></el-table-column>
          <el-table-column label="线索累计数" align="center" prop="sourceAccount"></el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-row style="margin: 10px 0" justify="space-between">
      <el-row>
        <el-button size="small" type="primary" @click="createActive">新建活动</el-button>
        <el-button size="small" type="default" @click="checkAll">全部活动</el-button>
      </el-row>
      <el-row>
        <el-button type="default" size="small" @click="showUpload">
          <el-icon color="var(--next-bg-menuBar-light-1)" size="16px">
            <ele-Upload/>
          </el-icon>
          客户导入
        </el-button>
        <el-button type="default" size="small" @click="setHeader">表头设置</el-button>
      </el-row>
    </el-row>
    <div class="table-box">
      <el-table size="small" :data="list" class="tableList">
        <el-table-column type="selection" width="30" fixed="left"></el-table-column>
        <el-table-column v-for="item in header" :key="item.id" :prop="item.label"
          :min-width="item.name.length > 4 ? `130px` : `90px`" align="center">
          <template #header>
            <span style="margin-right:2px;">{{ item.name }}</span>
            <!-- 可搜索表头 -->
            <el-popover placement="bottom" :width="100" trigger="click" v-if="item.isFilter && item.filter == 'search'">
              <template #reference>
                <el-icon :size="15" color="var(--el-color-primary)"><ele-Search /></el-icon>
              </template>
              <el-input :placeholder="`请输入${item.name}`" v-model.trim="search[item.label]" size="small" title="按下回车即可搜索"
                clearable @keydown.enter="bindSearch">
              </el-input>
            </el-popover>
            <!-- 可筛选表头 -->
            <el-popover placement="bottom" :width="60" trigger="click" @after-leave="bindSearch"
              v-if="item.isFilter && item.filter == 'filter'">
              <template #reference>
                <el-icon :size="15" color="var(--el-color-primary)"><ele-Filter /></el-icon>
              </template>
              <el-scrollbar max-height="600px">
                <el-radio-group v-model="search[item.label]" size="small"
                  v-if="filterList[item.label] && filterList[item.label].length > 0">
                  <el-radio v-for="radio in filterList[item.label]" :key="radio.name" :label="radio.name"
                    @click.prevent="onRadioChange(radio.name, item.label)">{{ radio.name }}</el-radio>
                </el-radio-group>
                <el-empty style="padding: 0;font-size:12px;" v-else :image-size="50" description="无数据" />
              </el-scrollbar>
            </el-popover>
          </template>
          <template #default="scope">
            <template v-if="item.label == 'name'">
              <el-tooltip effect="dark" :content="scope.row[item.label]" placement="top">
                <span class="primary short" @click="openDetail(scope.row)">{{ scope.row[item.label] }}</span>
              </el-tooltip>
            </template>
            <template v-else-if="item.label == 'sourcePrice'">
              <span v-if="scope.row.amountPaid != 0 && scope.row.addNumber != 0">{{ ((scope.row.amountPaid?scope.row.amountPaid:0) / (scope.row.addNumber?scope.row.addNumber:0)).toFixed(2) }}</span>
              <span v-else>0</span>
            </template>
            <template v-else>{{ scope.row[item.label] }}</template>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180px" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" link
              @click="del(scope.row, scope.$index)"><el-icon><ele-Delete /></el-icon>删除</el-button>
            <el-button size="small" type="primary" link @click="createCode(scope.row)"><i
                class="iconfont icon-barcode-qr"></i>生成二维码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-block">
      <el-pagination v-model:currentPage="search.current" v-model:page-size="search.size" :page-sizes="[10, 20, 30, 40]"
        :small="true" :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper"
        :total="total" :hide-on-single-page="true" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <active-create v-model:dialogDrawer="dialogCreate" @onSubmit="checkAll()"></active-create>
    <active-detail v-model:dialogDrawer="dialogDetail" :activeId="rowId" :form="detailData"
      @onSubmit="checkAll()"></active-detail>
    <el-image-viewer @close="closeImgViewer" :url-list="imageList" v-if="dialogCode" />
    <active-header v-model:dialogDrawer="dialogHeader" :default-header="header"></active-header>
    <!-- 阶段 -->
    <stage-setting v-model:dialogDrawer="dialogStage" @onShowStage="refreshStage"></stage-setting>
    <upload-model v-model:dialogDrawer="dialogUpload" @onSubmit="checkAll()"></upload-model>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ActiveCreate from '../components/ActiveCreate.vue'
import ActiveDetail from '../components/ActiveDetail.vue'
import ActiveHeader from '../components/ActiveHeader.vue'
import StageSetting from '../components/StageSetting.vue'
import UploadModel from '../components/UploadModel.vue'
import api from '/@/api/commonApi'

export default {
  name: 'MarketingList',
  components: {
    ActiveCreate,
    ActiveDetail,
    ActiveHeader,
    StageSetting,
    UploadModel
  },
  setup() {
    const state = reactive({
      year: 2022,
      accountList: [{
        reserveAccount: 0,
        outlayAccount: 0,
        leaseAccount: 0,
        sourceAccount: 0
      }],
      countStage: [],
      header: [{
        name: '活动主题',
        isFilter: true,
        filter: 'search',
        label: 'name'
      }, {
        name: '活动类型一级分类',
        isFilter: true,
        filter: 'filter',
        label: 'oneActivityName'
      }, {
        name: '活动类型二级分类',
        isFilter: true,
        filter: 'filter',
        label: 'twoActivityName'
      }, {
        name: '活动地点',
        isFilter: true,
        filter: 'filter',
        label: 'address'
      }, {
        name: '活动预算(元)',
        isFilter: false,
        filter: 'filter',
        label: 'budgetMoney'
      }, {
        name: '实际支出费用(元)',
        isFilter: false,
        filter: 'filter',
        label: 'amountPaid'
      }, {
        name: '新增线索数量',
        isFilter: false,
        filter: 'filter',
        label: 'addNumber'
      }, {
        name: '线索单价(元)',
        isFilter: false,
        filter: 'filter',
        label: 'sourcePrice'
      }, {
        name: '开始时间',
        isFilter: false,
        filter: 'filter',
        label: 'startTime'
      }, {
        name: '结束时间',
        isFilter: false,
        filter: 'filter',
        label: 'endTime'
      }, {
        name: '活动阶段',
        isFilter: true,
        filter: 'filter',
        label: 'stageName'
      }, {
        name: '活动负责人',
        isFilter: true,
        filter: 'filter',
        label: 'dutyUserName'
      }, {
        name: '备注',
        isFilter: false,
        filter: 'filter',
        label: 'remark'
      }
      ],
      list: [],
      filterList: {
        stageName: [],
        oneActivityName: [],
        twoActivityName: [],
        dutyUserName: [],
      },
      search: {
        current: 1,
        size: 10,
        type: 1,
        name: '',
        stageId: '',
        stageName: '',
        dutyUserId: '',
        dutyUserName: '',
        oneActivityId: '',
        oneActivityName: '',
        twoActivityId: '',
        twoActivityName: '',
      },
      total: 0,
      dialogCreate: false,
      rowId: '',
      dialogDetail: false,
      dialogCode: false,
      imageList: ['https://pic4.zhimg.com/bbcb8e8e842027a5022d6e00221ee6cf_r.jpg?source=1940ef5c'],
      dialogHeader: false,
      dialogStage: false,
      detailData: {},
      dialogUpload: false,
    })
    const openLifeSetting = () => {
      state.dialogStage = true
    }
    const setHeader = () => {
      state.dialogHeader = true
    }
    // 搜索
    const bindSearch = () => {
      getList()
    }
    // 选择搜索
    const onRadioChange = (val, name) => {
      state.search[name] = val
      getList()
    }
    // 条数切换
    const handleSizeChange = e => {
      state.search.size = e
      getList()
    }
    // 页码切换
    const handleCurrentChange = e => {
      state.search.current = e
      getList()
    }
    // 删除
    const del = (row, index) => {
      ElMessageBox.confirm(`是否确认删除「${row.name}」?`, '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        api.removeMarket({ ids: row.id }).then(res => {
          ElMessage.success('删除成功')
          getStageList()
          getList()
        })
      })
    }
    // 新建活动
    const createActive = () => {
      state.dialogCreate = true
    }
    // 全部活动
    const checkAll = () => {
      state.search = {
        current: 1,
        size: 10,
        type: 1,
        name: '',
        stageId: '',
        stageName: '',
        dutyUserId: '',
        dutyUserName: '',
        oneActivityId: '',
        oneActivityName: '',
        twoActivityId: '',
        twoActivityName: '',
      },
      getList()
      getStageList()
    }
    // 获取列表
    const getList = () => {
      api.marketList(state.search).then(res => {
        state.list = res.data.records
        state.total = res.data.total
      })
    }
    // 活动详情
    const openDetail = e => {
      api.marketDetail(e.id).then(res => {
        state.detailData = res.data
        state.rowId = res.data.id
        state.dialogDetail = true
      })
    }
    // 生成二维码
    const createCode = row => {
      state.dialogCode = true
    }
    // 关闭二维码
    const closeImgViewer = () => {
      state.dialogCode = false
    }
    // 获取显示头
    const getheaders = () => {
      api.stageList({ status: 1, type: 1 }).then(res => {
        state.header = JSON.parse(JSON.stringify(res.data))
      })
    }
    // 重新加载显示阶段
    const refreshStage = () => {
      getStageList()
    }
    // 获取企业人员列表
    const getEnterpriseUsers = () => {
      api.getEnterpriseUsers().then(res => {
        state.filterList.dutyUserName = res.data
      })
    }
    // 获取活动类型
    const getActivityType = (leaderId) => {
      api.getActivityType({ leaderId: leaderId }).then(res => {
        if (leaderId != '0') {
          state.filterList.twoActivityName = res.data
        } else {
          state.filterList.oneActivityName = res.data
        }
      })
    }
    // 获取活动阶段及统计
    const getStageList = () => {
      api.stageCountList().then(res => {
        state.filterList.stageName = res.data
        state.countStage = res.data
      })
    }
    // 录入活动客户
    const showUpload = () => {
      state.dialogUpload = true
    }

    onMounted(() => {
      getList()
      getEnterpriseUsers()
      getActivityType("0")
      getStageList()
    })
    return {
      ...toRefs(state),
      openLifeSetting,
      setHeader,
      bindSearch,
      handleSizeChange,
      handleCurrentChange,
      del,
      getheaders,
      onRadioChange,
      refreshStage,
      createActive,
      checkAll,
      openDetail,
      createCode,
      showUpload,
      closeImgViewer
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  .page-row {
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;

    .tips-data {
      display: flex;
      align-items: center;
      height: 28px;
      margin-top: 20px;

      .tips {
        margin-right: 3px;
        font-size: 13px;
      }

      &:first-child {
        height: unset;
        margin-top: 0;
      }
    }

    .tips-cell {
      flex: auto;

      .tips-item {
        display: flex;
        align-items: center;
        padding-left: 10px;
        justify-content: space-between;
      }

      .tips-name {
        margin-right: 10px;
        flex: 1;
        overflow: hidden;
        text-align: center;
      }

      .item-data {
        text-align: center;
        height: 28px;
        margin-top: 20px;
        line-height: 28px;
        color: var(--el-menu-text-color);
        font-size: 13px;
      }

      .text-red {
        font-size: 24px;
        color: red;
      }

      .item-right {
        margin-right: 14px;
      }

      .red {
        color: var(--el-color-danger)
      }

      .green {
        color: var(--el-color-success);
      }
    }

    :deep(.el-table--border::before),
    :deep(.el-table--border::after),
    :deep(.el-table__inner-wrapper::before),
    :deep(.el-table__border-left-patch) {
      display: none;
    }

    :deep(.el-table--border .el-table__inner-wrapper tr:first-child th:first-child),
    :deep(.el-table--border .el-table__inner-wrapper tr:first-child td:first-child) {
      border-left: none !important;
    }

    :deep(.el-table--border .el-table__cell:last-child) {
      border-right: none;
    }

    :deep(.el-table__row) {
      &:last-child {
        .el-table__cell {
          border-bottom: none;
        }
      }
    }
  }

  .table-box {
    background: #fff;
    margin-top: 10px;

    :deep(.el-table__header-wrapper .el-table__cell) {
      background: var(--el-color-primary-light-9);
      color: var(--next-bg-menuBar-light-1);
    }

    :deep(thead .cell) {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    :deep(thead .el-icon) {
      margin-top: -2px;
      cursor: pointer;
    }

    .primary {
      cursor: pointer;
      color: var(--el-color-primary);
    }

    .short {
      display: block;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}
</style>